﻿namespace WebUI.Controllers
{
    using System.Web.Mvc;
    using System.Web.Security;

    using KanbanBoard.Core.DataInterfaces;

    public class LoginController : Controller
    {
        private readonly IUserRepository userRepository;

        public LoginController(IUserRepository userRepository)
        {
            this.userRepository = userRepository;
        }

        [HttpGet]
        public ActionResult Login()
        {
            return View();
        }

        [HttpPost]
        public ActionResult Login(string userName, string password, string ReturnUrl)
        {
#if DEBUG
            userName = "admin";
            password = "secret";
#endif
            if (IsValidLoginArgument(userName, password))
            {
                if (userRepository.LogIn(userName, password) != null)
                    RedirectFromLoginPage(userName, ReturnUrl);
                else
                    ViewData["LoginFaild"] = "Login faild! Make sure you have entered the right user name and password!";
            }

            return View();
        }

        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();

            return View("Login");
        }

        private void RedirectFromLoginPage(string userName, string ReturnUrl)
        {
            FormsAuthentication.SetAuthCookie(userName, false);

            if (!string.IsNullOrEmpty(ReturnUrl))
                Response.Redirect(ReturnUrl);
            else
                Response.Redirect(FormsAuthentication.DefaultUrl);
        }

        private bool IsValidLoginArgument(string userName, string password)
        {
            return !(string.IsNullOrEmpty(userName) && string.IsNullOrEmpty(password));
        }

    }
}
